$(function () {
    let token = window.localStorage.getItem(token_key);
    let zCode = __zqApi.getWebURLKey("zcode");
    if (token == null) {
        if (zCode == null) {
            is_login = false;
            login_user = {};
            initAuth();
        } else {
            $.zjax({
                url: `${auth_proxy}`,
                zqMethod: "getJWTTokenByZCode",
                zqParams: JSON.stringify({"zcode": zCode}),
                async: false,
                success: function (res) {
                    let _res = JSON.parse(res);
                    if (_res.code == 200 && _res.data != null) {
                        let token = _res.data;
                        let d_payload = decodeURIComponent(escape(window.atob(token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/"))));
                        if (d_payload) {
                            let user_json = JSON.parse(d_payload);
                            let user = JSON.parse(user_json.user);
                            window.sessionStorage.setItem("zq-user", user_json.user);
                            login_user = user;
                            user_id = user.id;
                            is_login = true;
                            window.localStorage.setItem(token_key, token)
                        }
                    } else {
                        is_login = false;
                        login_user = {};
                    }
                    initAuth();
                }
            })
        }
    } else {
        if (zCode == null) {
            checkLoginUser(token);
        } else {
            // token 和 zcode 都不为null，而zcode仅有效一次
            $.zjax({
                url: `${auth_proxy}`,
                zqMethod: "getJWTTokenByZCode",
                zqParams: JSON.stringify({"zcode": zCode}),
                async: false,
                success: function (res) {
                    let _res = JSON.parse(res);
                    if (_res.code == 200 && _res.data != null) {
                        let token = _res.data;
                        let d_payload = decodeURIComponent(escape(window.atob(token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/"))));
                        if (d_payload) {
                            let user_json = JSON.parse(d_payload);
                            let user = JSON.parse(user_json.user);
                            window.sessionStorage.setItem("zq-user", user_json.user);
                            login_user = user;
                            user_id = user.id;
                            is_login = true;
                            window.localStorage.setItem(token_key, token)
                        }
                        initAuth();
                    } else {
                        checkLoginUser(token);
                    }
                }
            })
        }
    }
})

function checkLoginUser(token) {
    $.zAjax({
        type: "post",
        url: `${auth_proxy}`,
        async: false,
        zqMethod: "isTokenExpired",
        success: function (data) {
            let _data = JSON.parse(data);
            if (_data.data) {
                let d_payload = decodeURIComponent(escape(window.atob(token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/"))));
                if (d_payload) {
                    let user_json = JSON.parse(d_payload);
                    let user = JSON.parse(user_json.user);
                    window.sessionStorage.setItem("zq-user", user_json.user);
                    login_user = user;
                    user_id = user.id;
                    is_login = true;
                    window.localStorage.setItem(token_key, token);
                }
                initAuth();
            } else {
                is_login = false;
                login_user = {};
                initAuth();
            }
        }
    });
}

function initAuth() {
    if ($(".div-auth").length) {
        if (is_login) {
            $(".div-auth").append2(`
                    <a href="zq-user-profile.html?referrer=${encodeURIComponent(window.location.href)}"
                       class="flex h-11 w-11 items-center justify-center rounded-lg outline-none transition-colors duration-200 hover:bg-primary/20 focus:bg-primary/20 active:bg-primary/25 dark:hover:bg-navy-300/20 dark:focus:bg-navy-300/20 dark:active:bg-navy-300/25">
                        <svg class="h-7 w-7" viewbox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path fill-opacity="0.3" fill="currentColor"
                                  d="M2 12.947v-1.771c0-1.047.85-1.913 1.899-1.913 1.81 0 2.549-1.288 1.64-2.868a1.919 1.919 0 0 1 .699-2.607l1.729-.996c.79-.474 1.81-.192 2.279.603l.11.192c.9 1.58 2.379 1.58 3.288 0l.11-.192c.47-.795 1.49-1.077 2.279-.603l1.73.996a1.92 1.92 0 0 1 .699 2.607c-.91 1.58-.17 2.868 1.639 2.868 1.04 0 1.899.856 1.899 1.912v1.772c0 1.047-.85 1.912-1.9 1.912-1.808 0-2.548 1.288-1.638 2.869.52.915.21 2.083-.7 2.606l-1.729.997c-.79.473-1.81.191-2.279-.604l-.11-.191c-.9-1.58-2.379-1.58-3.288 0l-.11.19c-.47.796-1.49 1.078-2.279.605l-1.73-.997a1.919 1.919 0 0 1-.699-2.606c.91-1.58.17-2.869-1.639-2.869A1.911 1.911 0 0 1 2 12.947Z"></path>
                            <path fill="currentColor"
                                  d="M11.995 15.332c1.794 0 3.248-1.464 3.248-3.27 0-1.807-1.454-3.272-3.248-3.272-1.794 0-3.248 1.465-3.248 3.271 0 1.807 1.454 3.271 3.248 3.271Z"></path>
                        </svg>
                    </a>
                    <div x-data="usePopper({placement:'right-end',offset:12})"
                         @click.outside="isShowPopper && (isShowPopper = false)" class="flex">
                        <button @click="isShowPopper = !isShowPopper" x-ref="popperRef" class="avatar h-12 w-12">
                            <img class="rounded-full auth-image" src="${login_user.user_image}" alt="avatar">
                            <span class="absolute right-0 h-3.5 w-3.5 rounded-full border-2 border-white bg-success dark:border-navy-700"></span>
                        </button>
                        <div :class="isShowPopper && 'show'" class="popper-root fixed" x-ref="popperRoot">
                            <div class="popper-box w-64 rounded-lg border border-slate-150 bg-white shadow-soft dark:border-navy-600 dark:bg-navy-700">
                                <div class="flex user-bg items-center space-x-4 rounded-t-lg bg-slate-100 py-5 px-4 dark:bg-navy-800">
                                    <div class="avatar h-14 w-14">
                                        <img class="rounded-full" src="${login_user.user_image}" alt="avatar">
                                    </div>
                                    <div class="user-main">
                                        <a href="#"
                                           class="text-base user-username font-medium text-slate-700 hover:text-primary focus:text-primary dark:text-navy-100 dark:hover:text-accent-light dark:focus:text-accent-light">
                                            ${login_user.username}
                                        </a>
                                        <p class="text-xs user-description text-slate-400 dark:text-navy-300">
                                            ${login_user.user_description === undefined ? "这个人很神秘，没有留下个人简介。" : login_user.user_description}
                                        </p>
                                    </div>
                                </div>
                                <div class="flex flex-col pt-2 pb-5">
                                    <a href="#"
                                       class="group flex items-center space-x-3 py-2 px-4 tracking-wide outline-none transition-all hover:bg-slate-100 focus:bg-slate-100 dark:hover:bg-navy-600 dark:focus:bg-navy-600">
                                        <div class="flex h-8 w-8 items-center justify-center rounded-lg bg-warning text-white">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="h-4.5 w-4.5" fill="none"
                                                 viewbox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                                <path stroke-linecap="round" stroke-linejoin="round"
                                                      d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
                                            </svg>
                                        </div>
                                        <div>
                                            <h2 class="font-medium text-slate-700 transition-colors group-hover:text-primary group-focus:text-primary dark:text-navy-100 dark:group-hover:text-accent-light dark:group-focus:text-accent-light">
                                                个人简介
                                            </h2>
                                            <div class="text-xs text-slate-400 line-clamp-1 dark:text-navy-300">
                                                编辑你的个人资料
                                            </div>
                                        </div>
                                    </a>
                                    <a href="#"
                                       class="group flex items-center space-x-3 py-2 px-4 tracking-wide outline-none transition-all hover:bg-slate-100 focus:bg-slate-100 dark:hover:bg-navy-600 dark:focus:bg-navy-600">
                                        <div class="flex h-8 w-8 items-center justify-center rounded-lg bg-info text-white">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="h-4.5 w-4.5" fill="none"
                                                 viewbox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                                <path stroke-linecap="round" stroke-linejoin="round"
                                                      d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
                                            </svg>
                                        </div>
                                        <div>
                                            <h2 class="font-medium text-slate-700 transition-colors group-hover:text-primary group-focus:text-primary dark:text-navy-100 dark:group-hover:text-accent-light dark:group-focus:text-accent-light">
                                                消息
                                            </h2>
                                            <div class="text-xs text-slate-400 line-clamp-1 dark:text-navy-300">
                                                查看你所有的消息和通知
                                            </div>
                                        </div>
                                    </a>
                                    <a href="#"
                                       class="group flex items-center space-x-3 py-2 px-4 tracking-wide outline-none transition-all hover:bg-slate-100 focus:bg-slate-100 dark:hover:bg-navy-600 dark:focus:bg-navy-600">
                                        <div class="flex h-8 w-8 items-center justify-center rounded-lg bg-success text-white">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="h-4.5 w-4.5" fill="none"
                                                 viewbox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                                <path stroke-linecap="round" stroke-linejoin="round"
                                                      d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path>
                                                <path stroke-linecap="round" stroke-linejoin="round"
                                                      d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                                            </svg>
                                        </div>
                                        <div>
                                            <h2 class="font-medium text-slate-700 transition-colors group-hover:text-primary group-focus:text-primary dark:text-navy-100 dark:group-hover:text-accent-light dark:group-focus:text-accent-light">
                                                设置
                                            </h2>
                                            <div class="text-xs text-slate-400 line-clamp-1 dark:text-navy-300">
                                                修改网页设置
                                            </div>
                                        </div>
                                    </a>
                                    <div class="mt-3 px-4">
                                        <button class="btn btn-logout h-9 w-full space-x-2 bg-primary text-white hover:bg-primary-focus focus:bg-primary-focus active:bg-primary-focus/90 dark:bg-accent dark:hover:bg-accent-focus dark:focus:bg-accent-focus dark:active:bg-accent/90">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none"
                                                 viewbox="0 0 24 24" stroke="currentColor">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
                                                      d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"></path>
                                            </svg>
                                            <span>登出</span>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>`, function () {
                // 处理网易云背景,网易云背景先不处理了
                if (login_user.login_type == "wyy") {
                    // let wyyaccount=JSON.parse(login_user.extra_message);
                    // let bgImg=wyyaccount.backgroundUrl;
                    // $(".user-bg").css("background-image",`url(${bgImg})`)
                    //     .css("background-size","cover")
                    //     .css("background-position","center");
                    // $(".user-username").css("color","#fff");
                    // $(".user-description").css("color","#fff");
                    // $(".user-main").css("background-color"," rgba(0,0,0,.3)")
                }
                // 登出
                if ($(".btn-logout")) {
                    $(".btn-logout").click(function () {
                        $.zjax({
                            url: `${auth_proxy}`,
                            zqMethod: "logout",
                            type: "POST",
                            zqParams: JSON.stringify({
                                "logoutById": user_id
                            }),
                            xhrFields: {
                                withCredentials: true
                            },
                            success: function (res) {
                                window.localStorage.removeItem(token_key);
                                $.cookie(token_key, null, {path: '/'});
                                location.reload();
                            },
                            error: function () {

                            }
                        });
                    })
                }
            })
        } else {
            $(".div-auth").html(`
                    <div x-data="usePopper({placement:'right-end',offset:12})"
                         @click.outside="isShowPopper && (isShowPopper = false)" class="flex">
                        <button @click="isShowPopper = !isShowPopper" x-ref="popperRef" class="avatar h-12 w-12">
                            <img class="rounded-full auth-image" src="static/picture/200x200.png" alt="avatar">
                            <span class="absolute right-0 h-3.5 w-3.5 rounded-full border-2 border-white bg-error dark:border-navy-700"></span>
                        </button>
                        <div :class="isShowPopper && 'show'" class="popper-root fixed" x-ref="popperRoot">
                            <div class="popper-box w-64 rounded-lg border border-slate-150 bg-white shadow-soft dark:border-navy-600 dark:bg-navy-700">
                                <div class="flex items-center space-x-4 rounded-t-lg bg-slate-100 py-5 px-4 dark:bg-navy-800">
                                    <div class="avatar h-14 w-14">
                                        <img class="rounded-full" src="static/picture/200x200.png" alt="avatar">
                                    </div>
                                    <div>
                                        <a href="zq-login.html?redirect=${window.location.href}"
                                           class="text-base font-medium text-slate-700 hover:text-primary focus:text-primary dark:text-navy-100 dark:hover:text-accent-light dark:focus:text-accent-light">
                                            请登录
                                        </a>
                                        <p class="text-xs text-slate-400 dark:text-navy-300">
                                            登录以获得最佳体验
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>`)
        }
    }
}